package com.fresh.liangyi.service.impl;

import com.fresh.liangyi.dao.UserMapper;
import com.fresh.liangyi.model.domain.Authority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.fresh.liangyi.model.domain.User user=userMapper.getUserByName(username);
        //判断用户是否存在
        if(user!=null){
            //读取用户权限
            List<Authority> authorityList = userMapper.getAuthority(username);
            List list=new ArrayList<SimpleGrantedAuthority>();
            //对权限列表进行类型转换
            for(Authority authority:authorityList){
                list.add(new SimpleGrantedAuthority(authority.getAuthority()));
            }
            //构造UserDetails对象
            return new User(user.getUsername(),user.getPassword(),list);
        }else{
            throw  new UsernameNotFoundException("当前用户不存在");
        }
    }
}
